package ca

import (
	"html/template"
	"os"
	"os/exec"
	"path/filepath"

	"gitee.com/extrame/fb-runner/util"
	"gitee.com/extrame/fb-runner/version"
)

func Version() (version.Version, error) {
	cmd := exec.Command("fabric-ca-client", "version")
	bts, err := cmd.Output()
	if err == nil {
		return version.New(string(bts)), nil
	}
	return version.New(""), err
}

func Create(v version.Version, source, base, network string) error {

	util.Mkdir(filepath.Join(base, "/organizations/fabric-ca/org1"))
	util.Mkdir(filepath.Join(base, "/organizations/fabric-ca/org2"))
	util.Mkdir(filepath.Join(base, "/organizations/fabric-ca/ordererOrg"))
	// copy docker-compose file

	t, err := template.ParseFiles(filepath.Join(source, "docker/docker-compose-ca.yaml"))
	if err == nil {
		var f *os.File
		var dest = filepath.Join(base, "docker/docker-compose-ca.yaml")
		util.MkdirFor(dest)
		f, err = os.OpenFile(dest, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
		defer f.Close()
		if err == nil {
			data := make(map[string]interface{})
			data["CaImageTag"] = string(v)
			data["Organizations"] = util.Config.Organizations
			err = t.Execute(f, data)

			if err == nil {
				for name, org := range util.Config.Organizations {
					createDefaultConfigFile("admin", "adminpw", v.String(), org.Ca.GetHost(), filepath.Join(base, "/organizations/fabric-ca/"+name+"/fabric-ca-server-config.yaml"))
				}
			}
		}

	}

	return err
}

func Run(base, network string) error {
	cmd := exec.Command("docker-compose", "-p", network, "-f", "docker/docker-compose-ca.yaml", "up", "-d")
	cmd.Dir = base
	_, _, err := util.Run(cmd, true)
	return err
}
